<template>
  <w-view height="*">

    <w-vertical height="*" align="center">
        <p></p>
        <w-slider @drop="sliderDrop" width="500"></w-slider>
        <w-vertical height="*" ref="container" align="center" valign="middle">
          <canvas ref="canvas" :style="{width: `${canvasWidth}px`, height: `${canvasHeight}px`}"></canvas>
        </w-vertical>
    </w-vertical>

  </w-view>
</template>

<script setup>
  import $ from 'dfish-widget'
  import {ref, nextTick, onMounted} from 'vue'

  const canvas = ref()
  const canvasWidth = ref()
  const canvasHeight = ref()
  let ratio = 1
  let currentImageData
  let ctx
  let timer

  const sliderDrop = (e, v) => {
    v = parseInt(v)
    console.log(e, v)
    timer = setTimeout(() => {
      console.time('wasm')
      const blurData = Module.asmGamma(currentImageData.data, currentImageData.height, currentImageData.width, v)
      const cvData = new ImageData(new Uint8ClampedArray(blurData), currentImageData.width, currentImageData.height);
      console.timeEnd('wasm')
      ctx.putImageData(cvData, 0, 0)
    }, 10)
  }

  const getPixelRatio = (context) => {
    let backingStore = context.backingStorePixelRatio ||
      context.webkitBackingStorePixelRatio ||
      context.mozBackingStorePixelRatio ||
      context.msBackingStorePixelRatio ||
      context.oBackingStorePixelRatio ||
      context.backingStorePixelRatio || 1;
    return (window.devicePixelRatio || 1) / backingStore;
  }

  const init = () => {
    ctx = canvas.value.getContext('2d')
    const img = new Image()
    const maxw = 1000
    const maxh = 1000
    img.src = 'assets/images/qingdao.jpg'
    img.onload = () => {
      let cp = maxw / maxh
      let ip = img.width / img.height
      let cw = maxw
      let ch = maxh
      if (ip > cp) {
        cw = Math.min(maxw, img.width)
        ch = cw / ip
      } else {
        ch = Math.min(maxh, img.height)
        cw = ch * ip
      }

      ctx.mozImageSmoothingEnabled = false;
      ctx.webkitImageSmoothingEnabled = false;
      ctx.msImageSmoothingEnabled = false;
      ctx.imageSmoothingEnabled = false;

      ratio = getPixelRatio(ctx)
      cw *= ratio
      ch *= ratio

      canvasWidth.value = cw / ratio
      canvasHeight.value = ch / ratio

      canvas.value.width = cw
      canvas.value.height = ch

      ctx.drawImage(img, 0, 0, cw, ch)
      currentImageData = ctx.getImageData(0, 0, cw, ch)
    }
  }

  onMounted(init)
</script>

<style>
</style>
